package com.yuwei.goods_shopping

import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.yuwei.base.RoutePath
import com.yuwei.common.mvi.BaseMviActivity
import com.yuwei.common.mvi.UiState
import com.yuwei.database.entity.OrderEntity
import com.yuwei.goods_shopping.adapter.GoodsShoppingAdapter
import com.yuwei.goods_shopping.databinding.ActivityGoodsShoppingBinding
import com.yuwei.common.entity.AddCarEntity
import com.yuwei.goods_shopping.entity.DeleteCarBody
import com.yuwei.goods_shopping.entity.GoodsShoppingEntity
import com.yuwei.goods_shopping.entity.GoodsShoppingEntityItem
import com.yuwei.goods_shopping.mvi.GoodsShoppingIntent
import com.yuwei.goods_shopping.mvi.GoodsShoppingVIewModel

@Route(path = RoutePath.GOODS_SHOPPING)
class GoodsShoppingActivity :
    BaseMviActivity<ActivityGoodsShoppingBinding, GoodsShoppingVIewModel>() {
    private lateinit var goodsShoppingAdapter: GoodsShoppingAdapter
    private var show = false
    private var check = false
    private var mPosition = 0
    private val goodsCarList = mutableListOf<GoodsShoppingEntityItem>()
    override fun successData(it: UiState.onSuccess<*>) {
        when (it.type) {
            "goodsSelectCar" -> {
                val data = it.data as GoodsShoppingEntity
                binding.goodsShoppingTop.text = if (goodsShoppingAdapter.itemCount != 0) "购物车(${goodsShoppingAdapter.itemCount})" else "购物车"
                goodsCarList.clear()
                goodsCarList.addAll(data)
                goodsShoppingAdapter.notifyDataSetChanged()
            }
            "deleteCar" -> {
                vm.sendIntent(GoodsShoppingIntent.goodsSelectCar)
                binding.money.text = " ￥ 0 元"
                binding.goodsShoppingAddBtn.isChecked = false
            }
        }
    }

    override fun failureData(error: String) {

    }

    override fun initView() {
        //列表
        goodsShoppingAdapter = GoodsShoppingAdapter(goodsCarList)
        binding.goodsShoppingRv.adapter = goodsShoppingAdapter
        binding.goodsShoppingRv.layoutManager = LinearLayoutManager(this)
        vm.sendIntent(GoodsShoppingIntent.goodsSelectCar)
        //点击管理
        binding.supervise.setOnClickListener {
            show = !show
            if (show) binding.supervise.setText("完成") else binding.supervise.setText("管理")
            if (show) binding.goodsShoppingMoney.setText("删除") else binding.goodsShoppingMoney.setText(
                "结算"
            )
            goodsShoppingAdapter.setIsShow(show)
            goodsShoppingAdapter.notifyDataSetChanged()
        }
        //全选按钮
        binding.goodsShoppingAddBtn.setOnCheckedChangeListener { button, isCheck ->
            check = isCheck
            binding.goodsShoppingAddBtn.setOnClickListener {
                goodsCarList.forEach {
                    it.check = isCheck
                }
                goodsShoppingAdapter.notifyDataSetChanged()
                totalmaney()
            }
        }
        //点击结算
        binding.goodsShoppingMoney.setOnClickListener {
            if (show) {
                val selectedItems = goodsCarList.filter { it.check }
                if (selectedItems.isEmpty()) {
                    ToastUtils.showLong("还没有选商品呦~")
                    return@setOnClickListener
                }
                AlertDialog.Builder(this)
                    .setTitle("删除提醒")
                    .setMessage("确定要删除已勾选的吗?")
                    .setPositiveButton("确定") { dialog, _ ->
                        goodsCarList.forEach {
                            if (it.check) {
                                vm.sendIntent(GoodsShoppingIntent.DeleteCar(DeleteCarBody(it.id.toString())))
                                goodsShoppingAdapter.notifyDataSetChanged()
                            }
                        }
                        dialog.dismiss()
                    }
                    .setNegativeButton("取消") { dialog, _ ->
                        dialog.dismiss()
                    }
                    .show()
            } else {
                if (!goodsCarList.any { it.check }) {
                    ToastUtils.showLong("还没有选商品呦~")
                    return@setOnClickListener
                }
                val list = mutableListOf<OrderEntity>()
                goodsCarList.forEach {
                    if (it.check){
                        list.add(OrderEntity(0,it.count,it.goods_default_icon,it.goods_default_price,it.goods_desc,it.goods_id,it.user_id,it.order_id))
                    }
                }

                goodsCarList.forEach {
                    if (it.check){
                        vm.sendIntent(GoodsShoppingIntent.insertOrder(OrderEntity(0,it.count,it.goods_default_icon,it.goods_default_price,it.goods_desc,it.goods_id,it.user_id,0)))
                        vm.sendIntent(GoodsShoppingIntent.DeleteCar(DeleteCarBody(it.id.toString())))
                        goodsShoppingAdapter.notifyDataSetChanged()
                    }
                }
                ARouter.getInstance().build(RoutePath.MODULE_ORDER_CONFIRM_ORDER_ACTIVITY) .navigation()

            }

        }

        //增加，删除
        goodsShoppingAdapter.setItemOnClickListener(object :
            GoodsShoppingAdapter.OnItemClickListener {
            override fun onItemClick(v: View, position: Int) {

                when (v.id) {
                    R.id.goods_car_rv_check -> {
                        goodsCarList[position].check = !goodsCarList[position].check
                    }
                    R.id.goods_car_btn_add -> {
                        goodsCarList[position].count++
                        vm.sendIntent(
                            GoodsShoppingIntent.AddCar(
                                AddCarEntity(
                                    1,
                                    goodsCarList[position].goods_id
                                )
                            )
                        )
                        goodsShoppingAdapter.notifyItemChanged(position)
                    }
                    R.id.goods_car_btn_subtract -> {
                        if (goodsCarList[position].count == 1) {
                            return
                        }
                        goodsCarList[position].count--
                        vm.sendIntent(
                            GoodsShoppingIntent.AddCar(
                                AddCarEntity(
                                    -1,
                                    goodsCarList[position].goods_id
                                )
                            )
                        )
                        goodsShoppingAdapter.notifyItemChanged(position)
                    }
                    R.id.goods_car_delete -> {
                        AlertDialog.Builder(v.context)
                            .setTitle("删除提醒")
                            .setMessage("确定要删除吗?")
                            .setPositiveButton("确定") { dialog, _ ->
                                vm.sendIntent(
                                    GoodsShoppingIntent.DeleteCar(
                                        DeleteCarBody(
                                            goodsCarList[position].id.toString()
                                        )
                                    )
                                )
                                dialog.dismiss()
                            }
                            .setNegativeButton("取消") { dialog, _ ->
                                dialog.dismiss()
                            }
                            .show()
                    }

                }
                totalmaney()
                checkAll()
            }
        })
        //返回
        binding.goodsShoppingBack.setOnClickListener {
            finish()
        }
    }

    //全选的逻辑
    private fun checkAll() {
        val list = mutableListOf<Boolean>()
        goodsCarList.forEach {
            list.add(it.check)
        }
        binding.goodsShoppingAddBtn.isChecked = false !in list
    }

    //总价钱
    private fun totalmaney() {
        var money = 0
        goodsCarList.forEach {
            if (it.check) {
                money += it.count * it.goods_default_price
            }
        }
        binding.money.text = " ￥$money 元"
    }

    override fun initData() {

    }

}